<?php

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

/**
 * @package app\admin\controller
 */
class CdkeyController extends AdminBaseController
{

    public function index()
    {   

        $condition['c.delete_at'] =0;
        if (input('param.keys')) {
            $condition['c.keys'] = input('param.keys');
        }
        $rows =  Db::name('cdkey')
                  ->alias('c')
                  ->join('cdkey_category cc','c.category_id=cc.id','left')
                  ->field('c.*,cc.title category_title')
                  ->where($condition)
                  ->order('id desc')
                  ->paginate(10);
        $this->assign('rows', $rows);
        return $this->fetch();
    }

    function uptag()
    {
        if ($_POST) {
            $id = $this->request->param('id');
            $tag = $this->request->param('tag');
            $type = $this->request->param('type');

            $isdel = Db::name('cdkey')->where(['id' => $id])->update([$tag => $type]);
            if ($isdel !== false) {
                echo "修改状态成功！";
            } else {
                echo "修改状态失败！";
            }
        }
    }


    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    private function getRandomStr($len, $special = true)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }


    public function add()
    {
        if ($_POST) {
            $category_id = input('param.category_id/d');
            if($category_id<=0){
                $this->error('请选择类别');
            }
            $num    = $this->request->param('num', 0, 'intval');
            if ($num < 1) {
                $this->error('数量不正确');
            }

            $data = array();
            for ($i = 0; $i < $num; $i++) {
                $item = array();
                $item['keys'] = $this->getRandomStr(8, false);
                $item['selled'] = 0;
                $item['ctime'] = time();
                $item['status'] = 1;
                $item['category_id'] = $category_id;
                $data[] = $item;
            }

            //var_dump($data);
            $result    = Db::name('cdkey')->insertAll($data);
            if ($result === false) {
                $this->error(Db::name('cdkey')->getError());
            }

            $this->success("添加成功！", url("Cdkey/index"));
        }
        $categorys =  Db::name('cdkey_category')->where('delete_at',0)->order('term desc')->select()->toArray();
        $this->assign('categorys', $categorys);
        return $this->fetch();
    }
    public function edits()
    {
        $server = $_SERVER['HTTP_HOST'];
        $id    = $this->request->param('id', 0, 'intval');
        $good_data =  Db::name('cdkey')->where('id', $id)->find();
        $this->assign('server', $server);
        $this->assign('good_data', $good_data);
        return $this->fetch();
    }

    public function editpost()
    {
        $data      = $this->request->param();

        $result    = Db::name('cdkey')->update($data);
        if ($result === false) {
            $this->error(Db::name('cdkey')->getError());
        }
        $this->success("保存成功！", url("Cdkey/index"));
    }

    public function del()
    {
        $id = $this->request->param('id', 0, 'intval');
        Db::name('cdkey')->where("id = $id")->delete();
        $this->success("删除成功！", url("Cdkey/index"));
    }

    public function log()
    {


        $where   = [];
        $request = $this->request->param();

        if (!empty($request['keys'])) {
            $where['keys'] = htmlspecialchars($request['keys']);
        }
        $query = Db::name('CdkeyLogs');

        $datas = $query->where($where)->order("id DESC")->paginate(20);


        // 获取分页显示
        $page = $datas->render();


        $this->assign('datas', $datas);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }




    //类别
    function  category(){
        $data =  Db::name('cdkey_category')->where('delete_at',0)->order('id desc')->select()->toArray();
        $this->assign('datas', $data);
        return $this->fetch();
    }


    function addcategory(){
        if(request()->isPost()){
            $data = input('param.');
            if(empty($data['title']) || $data['price']<=0){
                return $this->error('名称不能为空,价格必须大于0');
            }
            $row=Db::name('cdkey_category')->where(['term'=>$data['term'],'delete_at'=>0])->find();
            $insertdata = [
                    'title'=>$data['title'],
                    'term'=>$data['term'],
                    'price'=>$data['price'],
                    'create_at'=>time()
                ];
            if($row){
                Db::name('cdkey_category')->where('id',$row['id'])->update($insertdata);
            }else{
                Db::name('cdkey_category')->insert($insertdata);
            }
           
            $this->redirect(url('category'));
        }
        $this->assign('row',[]);
        $this->assign('action',url('addcategory'));
        return $this->fetch('editcategory');
    }


    function editcategory(){
        $data = input('param.');
        if($data['id']<=0){
            return $this->error('参数错误');
        }
        if(request()->isPost()){
            
            if(empty($data['title']) || $data['price']<=0){
                return $this->error('名称不能为空,价格必须大于0');
            }
            Db::name('cdkey_category')
                ->where('id',$data['id'])
                ->update([
                    'title'=>$data['title'],
                    'term'=>$data['term'],
                    'price'=>$data['price'],
                    'create_at'=>time()
                ]);
            $this->redirect(url('category'));
        }
        $row = Db::name('cdkey_category')->where('id',$data['id'])->find();
        $this->assign('row',$row);
        $this->assign('action',url('editcategory'));
        return $this->fetch('editcategory');
    }



    function delcategory(){
        $data = input('param.');
        if($data['id']<=0){
            return $this->error('参数错误');
        }
        Db::name('cdkey_category')->where('id',$data['id'])->update(['delete_at'=>time()]);
        return $this->fetch('editcategory');
    }
}
